package com.malty.utils;

import lombok.Data;

import java.io.*;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @author malty
 */
@Data
public class RemoveFileDupContent {
    private String path;
    private File file;
    private BufferedReader bufferedReader;
    private FileReader fileReader;
    private BufferedWriter bufferedWriter;
    private FileWriter fileWriter;
    private Set<String> filecontent;
    private List<String> content;


    public static void main(String[] args) throws IOException {
        String path = "";
        RemoveFileDupContent fileContent = new RemoveFileDupContent(path);
        fileContent.removeDupContent();
    }

    public RemoveFileDupContent(String path) {
        this.path = path;
        file = new File(path);
        filecontent = new HashSet<>();
        try {
            fileReader = new FileReader(file);
            bufferedReader = new BufferedReader(fileReader);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }

    private void destroy() throws IOException {
        fileWriter.close();
        fileReader.close();
        bufferedWriter.close();
        bufferedReader.close();
    }

    private void readFile() throws IOException {
        String s = null;
        while ((s = bufferedReader.readLine()) != null) {
            if (!filecontent.contains(s)) {
                filecontent.add(s);
                content.add(s);
            }
        }
        writeFile();
    }

    private void writeFile() throws IOException {
        fileWriter = new FileWriter(file);
        bufferedWriter = new BufferedWriter(fileWriter);
        for (String s : filecontent) {
            bufferedWriter.write(s);
            bufferedWriter.newLine();
        }
        bufferedWriter.flush();
    }

    public void removeDupContent() throws IOException {
        readFile();
        destroy();
    }
}
